#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include "gaia_init_socket.h"


/********************
 * 函数名：gaia_init_socket
 * 函数功能：初始化sock，包括绑定地址，监听端口
 * 函数返回值：成功　0，失败 -1
*/
int gaia_init_socket(int *listen_fd,struct sockaddr_in *server_addr)
{
  if((*listen_fd = socket(AF_INET,SOCK_STREAM,0) ) == -1)
  {
    perror("socket error");
    return -1;
  }

  //地址端口复用
  int opt = SO_REUSEADDR;
  if(setsockopt(*listen_fd,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt)) == -1)
  {
    perror("setsockopt error");
    return -1;
  }

  server_addr->sin_family = AF_INET;
  server_addr->sin_port = htons(PORT);
  server_addr->sin_addr.s_addr = htonl(INADDR_ANY);

  //绑定地址
  if(bind(*listen_fd,(struct sockaddr *)server_addr,sizeof(struct sockaddr_in )) == -1)
  {
    perror("bind error");
    return -1;
  }

  //设置监听
  if(listen(*listen_fd,BACKLOG) == -1)
  {
    perror("listen error");
    return -1;
  }

  return 0;
}
